%% generateRubImpactForce
% generate a 'rubImpactForce.m' file
%% Syntax
% generateRubImpactForce(RubImpact, Mesh)
%% Description
% RubImpact: is a struct saving the relevant data
%
% Mesh: is a struct saving the information about meshing
%
% generate a rubImpactForce.m file in the root directory


function generateRubImpactForce(RubImpact, Mesh)

% check the exist of rubImpactForce and create .txt
if isfile('rubImpactForce.m')
    delete rubImpactForce.m
end

rif = fopen('rubImpactForce.txt','w');

%%

% write comments, firstly

comments = [...
"%% rubImpactForce";...
"% saving the equation of rub-impact force in this function";...
"%% Syntax";...
"% fRub = rubImpactForce(qn)";...
"%% Description";...
"% qn: is the displacement at the n-th time";...
"% ";...
"% fRub: is rub-impact force (vector)";...
" ";...
" "...
];

%%

% function start
functionStart = [...
"function fRub = rubImpactForce(qn)";...
" "...
];

fprintf(rif,'%s\n',comments);
fprintf(rif,'%s\n',functionStart);

%%

% calculate the number of dof for rub-impact force
rubDof = Mesh.dofInterval(RubImpact.positionOnShaftNode,:)';
rubDof = rubDof(1,:);


functionBody = {...
['kRub   = [', num2str(RubImpact.stiffness), '];'];...
['mu     = [', num2str(RubImpact.coefficientOfFriction), '];'];...
['delta  = [', num2str(RubImpact.interval), '];'];...
['rubDof = [', num2str(rubDof), '];'];...
 ' ';...
 ' ';...
['fRub = zeros(', num2str(Mesh.dofNum), ',1);'];...
['for iRub = 1:1:', num2str(RubImpact.amount)];...
 '    e = sqrt(qn(rubDof(iRub))^2 + qn(rubDof(iRub)+1)^2);';...
 '    if e >= delta(iRub)';...
 '       fRub(rubDof(iRub))   = kRub(iRub)*(1-delta/e) * (qn(rubDof(iRub)) - mu*qn(rubDof(iRub)+1));';...
 '       fRub(rubDof(iRub)+1) = kRub(iRub)*(1-delta/e) * (mu*qn(rubDof(iRub)) + qn(rubDof(iRub)+1));';...
 '    end';...
 'end';...
 ' ';...
};

functionBody = cell2string(functionBody);

fprintf(rif,'%s\n', functionBody);

%%

% function end
functionEnd = [...
"end";...
" "...
];
fprintf(rif,'%s\n',functionEnd);

%%

% close .txt and transfer .txt -> .m
fclose(rif);
system('rename rubImpactForce.txt rubImpactForce.m');
end